﻿using System;
using System.Configuration;
using System.Net;
using System.Web;
using App_Code.Facebook;
using App_Code.Helpers;
using App_Code.Logic;
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth2;

namespace OAuth
{
    public partial class OAuth_Facebook : System.Web.UI.Page
    {
        private static readonly FacebookClient client = new FacebookClient
        {
            ClientIdentifier = ConfigurationManager.AppSettings["facebookAppID"],
            ClientSecret = ConfigurationManager.AppSettings["facebookAppSecret"],
        };

        protected void Page_Load(object sender, EventArgs e)
        {
            IAuthorizationState authorization = client.ProcessUserAuthorization();
            if (authorization == null)
            {
                // Kick off authorization request
                client.RequestUserAuthorization();
            }
            else
            {
                var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
                using (var response = request.GetResponse())
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        var graph = FacebookGraph.Deserialize(responseStream);
                        SessionLogic.SessionAuthenticatedOpenAuth(PageHelper.VisualCronSession, graph.Link.AbsoluteUri, String.Format("{0} {1}", graph.FirstName, graph.LastName));
                        Response.Redirect("~/Default.aspx");
                    }
                }
            }
        }
    }
}